﻿using yao.Entity;
using yao.Mvc;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Titan;

namespace yao.website.Controllers
{
    /// <summary>
    /// 订单
    /// </summary>
    public class SalesOrderController:BaseController
    {
        #region private
        private string GenerateSalesOrderNo()
        {
           Random random=  new Random();
           StringBuilder sb=new StringBuilder(DateTime.Now.ToString("yyMMdd"));
            for (var i = 0; i < 8; i++)
            {
                sb.Append(random.Next(0,9));
            }
            return sb.ToString();
        }
        /// <summary>
        /// 查询订单行
        /// </summary>
        /// <param name="cn"></param>
        /// <param name="salesOrderId"></param>
        /// <returns></returns>
        private SalesOrderLines GetSalesOrderLines(IDbSession cn, long salesOrderId)
        {
            QueryExpression q = new QueryExpression();
            q.EntityType = typeof(SalesOrderLine);
            q.Selects.Add(SalesOrderLine_.SalesOrderId);
            q.Selects.Add(SalesOrderLine_.ProductName);//商品名称
            q.Selects.Add(SalesOrderLine_.ProductNo);//商品编号
            q.Selects.Add(SalesOrderLine_.CustomerProductNo);//客户方商品编号
            q.Selects.Add(SalesOrderLine_.Spec);//规格
            q.Selects.Add(SalesOrderLine_.LotNo);//批号
            q.Selects.Add(SalesOrderLine_.Unit);//单位
            q.Selects.Add(SalesOrderLine_.Quantity);//数量
            q.Selects.Add(SalesOrderLine_.Price);//单价
            q.Selects.Add(SalesOrderLine_.Amount);//金额
            q.Selects.Add(SalesOrderLine_.Remark);//备注
            q.Wheres.Add(SalesOrderLine_.SalesOrderId.TEqual(salesOrderId));
            SalesOrderLines salesOrderLines = new SalesOrderLines();
            cn.SelectCollection(salesOrderLines.Items, q);
            return salesOrderLines;
        }
        /// <summary>
        /// 获取表单提交过来的订单行
        /// </summary>
        /// <param name="salesOrderId"></param>
        /// <returns></returns>
        private SalesOrderLines GetSalesOrderLines(long salesOrderId)
        {
            #region salesOrderLines 订单行
            int salesOrderLineRow = 0;
            SalesOrderLines salesOrderLines = new SalesOrderLines();
            if (int.TryParse(Request.Form["SalesOrderLineRow"], out salesOrderLineRow))
            {
                for (var i = 0; i < salesOrderLineRow; i++)
                {

                    decimal Quantity;
                    decimal.TryParse(Request.Form["Quantity_" + i], out Quantity);//数量

                    long ProductId = 0;
                    long.TryParse(Request.Form["ProductId_" + i], out ProductId);//商品ID

                    string ProductName = Request.Form["ProductName_" + i];//商品名称
                    string Unit = Request.Form["Unit_" + i];//单位

                    decimal Price;
                    decimal.TryParse(Request.Form["Price_" + i], out Price);//单价

                    decimal Amount;
                    decimal.TryParse(Request.Form["Amount_" + i], out Amount);//金额
                    if (Amount != Price * Quantity)
                    {
                        Amount = Price * Quantity;
                    }

                    string Remark = Request.Form["Remark_" + i];
                    string ProductNo = Request.Form["ProductNo_" + i];
                    string CustomerProductNo = Request.Form["CustomerProductNo_" + i];
                    string Barcode = Request.Form["Barcode_" + i];
                    string Spec = Request.Form["Spec_" + i];
                    string LotNo = Request.Form["LotNo_" + i];

                    long SalesOrderLineId;
                    long.TryParse(Request.Form["SalesOrderLineId_" + i], out SalesOrderLineId);

                    if (string.IsNullOrEmpty(ProductNo) || string.IsNullOrEmpty(LotNo) || Quantity <= 0 || Price <= 0)
                    {
                        continue;
                    }
                    SalesOrderLine salesOrderLine = new SalesOrderLine
                    {
                        ProductNo = ProductNo,
                        CustomerProductNo = CustomerProductNo,
                        ProductId = ProductId,
                        ProductName = ProductName,
                        Quantity = Quantity,
                        Unit = Unit,
                        Price = Price,
                        Amount = Amount,
                        Barcode = Barcode,
                        Spec = Spec,
                        LotNo = LotNo,
                        Remark = Remark,
                        SalesOrderId = salesOrderId,
                        SalesOrderLineId = SalesOrderLineId
                    };
                    salesOrderLines.Items.Add(salesOrderLine);
                }
            }
            return salesOrderLines;
            #endregion
        }
        /// <summary>
        /// 修改商品表锁定数量，可用数量，总数量
        /// </summary>
        /// <param name="quantity"></param>
        /// <param name="productId"></param>
        private void UpdateProduct(IDbSession cn, decimal quantity, long productId)
        {
            MySqlCommand cmdProduct = new MySqlCommand("update Product set LockCount=LockCount+@LockCount,UseableCount=UseableCount+@UseableCount where ProductId=@ProductId");
            cmdProduct.Parameters.AddWithValue("@LockCount", quantity);
            cmdProduct.Parameters.AddWithValue("@UseableCount", -quantity);
            cmdProduct.Parameters.AddWithValue("@ProductId", productId);
            cn.ExecuteNonQuery(cmdProduct);
        }
        /// <summary>
        /// 修改商品库存表锁定数量，可用数量，总数量
        /// </summary>
        /// <param name="cn"></param>
        /// <param name="quantity"></param>
        /// <param name="productId"></param>
        /// <param name="lotNo"></param>
        /// <param name="storeId"></param>
        private void UpdateStoreProduct(IDbSession cn, decimal quantity, long productId, string lotNo, long storeId)
        {
            MySqlCommand cmdStoreProduct = new MySqlCommand("update StoreProduct set UseableQuantity=UseableQuantity+@UseableQuantity,LockQuantity=LockQuantity+@LockQuantity where ProductId=@ProductId and LotNo=@LotNo and StoreId=@StoreId and QualityStyleId=1");
            cmdStoreProduct.Parameters.AddWithValue("@UseableQuantity", -quantity);
            cmdStoreProduct.Parameters.AddWithValue("@LockQuantity", quantity);
            cmdStoreProduct.Parameters.AddWithValue("@ProductId", productId);
            cmdStoreProduct.Parameters.AddWithValue("@LotNo", lotNo);
            cmdStoreProduct.Parameters.AddWithValue("@StoreId", storeId);
            cn.ExecuteNonQuery(cmdStoreProduct);
        }

        #endregion

        public ActionResult Index(int? t, int? p)
        {
            int pageIndex = p == null ? 1 : (int)p;
            ViewBag.PageIndex = pageIndex;

            using (IDbSession cn = OpenSession())
            {
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(SalesOrder);
                q.Selects.Add(SalesOrder_.SalesOrderId);
                q.Selects.Add(SalesOrder_.SalesOrderNo);//销售单号
                q.Selects.Add(SalesOrder_.CustomerId);//客户
                q.Selects.Add(SalesOrder_.Customer.CustomerName);//客户
                q.Selects.Add(SalesOrder_.Address);//收货人
                q.Selects.Add(SalesOrder_.ContactName);//收货人
                q.Selects.Add(SalesOrder_.CreateTime);//创建时间
                q.Selects.Add(SalesOrder_.OrderEmployeeId);//业务员ID
                q.Selects.Add(SalesOrder_.OrderEmployee.EmployeeName);//业务员ID
                q.Selects.Add(SalesOrder_.Phone);//联系电话
                q.Selects.Add(SalesOrder_.Amount);//订单金额
                q.Selects.Add(SalesOrder_.ActualAmount);//实际金额
                q.Selects.Add(SalesOrder_.IsCompleted);//是否结束
                q.Selects.Add(SalesOrder_.IsDraft);//是否草稿订单
                q.Selects.Add(SalesOrder_.DeliveryStatusId);//交货状态
                q.Selects.Add(SalesOrder_.SettleStatusId);//结款状态
                q.Wheres.Add(SalesOrder_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                if (t != null)
                {
                    switch (t)
                    {
                        case 1://草稿订单
                            q.Wheres.Add(SalesOrder_.IsDraft.TEqual(true));
                            break;
                        case 2://未交货
                            q.Wheres.Add(SalesOrder_.DeliveryStatusId.TEqual(1));
                            break;
                        case 3://未结款
                            q.Wheres.Add(SalesOrder_.SettleStatusId.TEqual(1));
                            break;
                        case 4://已结束
                            q.Wheres.Add(SalesOrder_.IsCompleted.TEqual(true));
                            break;
                        default:
                            break;
                    }
                }
                q.PageIndex = pageIndex;
                q.PageSize = 20;
                q.OrderBy(SalesOrder_.SalesOrderId.Desc);
                q.ReturnMatchedCount = true;
                SalesOrders SalesOrders = new SalesOrders();
                SalesOrders.TotalCount = cn.SelectCollection(SalesOrders.Items, q);
                return View(SalesOrders);
            }
        }

        public ActionResult Edit(long? id)
        {
            SalesOrder salesOrder = new SalesOrder();
            if (id != null)
            {
                ViewBag.Title = "修改订单-" + id;
                salesOrder.SalesOrderId = (long)id;
                #region 查询订单行表
                using (IDbSession cn = OpenSession())
                {
                    cn.Select(salesOrder,SalesOrder_.ALL,SalesOrder_.OrderEmployee.EmployeeName,SalesOrder_.Customer.CustomerName, SalesOrder_.Store.StoreName);
                    salesOrder.SalesOrderLines = GetSalesOrderLines(cn,salesOrder.SalesOrderId);
                }
                #endregion
            }
            else {
                salesOrder.SalesOrderNo = GenerateSalesOrderNo();
                salesOrder.DeliveryTypeId = DeliveryType.Delivery;//配送
                salesOrder.PlanDeliveryTime = DateTime.Now.AddDays(1);//配送时间
                salesOrder.SalesOrderLines = new SalesOrderLines();
            }
            return View(salesOrder);
        }

        #region 修改订单
        [HttpPost]
        public ActionResult Edit(long? id, SalesOrder salesOrder)
        {
            #region 验证
            Validate(salesOrder, SalesOrder_.SalesOrderNo);
            Validate(salesOrder, SalesOrder_.CustomerId);
            Validate(salesOrder, SalesOrder_.OrderEmployeeId);
            Validate(salesOrder, SalesOrder_.IsMapped);
            Validate(salesOrder, SalesOrder_.X);
            Validate(salesOrder, SalesOrder_.Y);
            #endregion

            if (!IsValid)
            {
                salesOrder.SalesOrderLines = new SalesOrderLines();
                return View(salesOrder);
            }

            using (IDbSession cn = OpenSession())
            {
                cn.BeginTransaction();
                try
                {
                    salesOrder.CompanyId = CurrentEmployee.CompanyId;
                    //添加
                    if (id == null)
                    {
                        #region 添加
                        #region validate
                        ConditionExpressionCollection cs = new ConditionExpressionCollection();
                        cs.Add(SalesOrder_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                        cs.Add(SalesOrder_.SalesOrderNo.TEqual(salesOrder.SalesOrderNo));
                        if (cn.Exists<SalesOrder>(cs))
                        {
                            AddFormError(SalesOrder_.SalesOrderNo, "订单编号不允许重复");
                        }
                        //现场收款金额
                        if (string.IsNullOrEmpty(Request.Form["SalesOrderCapitalAmount"]))
                        {
                            AddFormError("SalesOrderCapitalAmount", "现场收款金额不允许空");
                        }
                        decimal salesOrderCapitalAmount;
                        if (!decimal.TryParse(Request.Form["SalesOrderCapitalAmount"], out salesOrderCapitalAmount)) {
                            AddFormError("SalesOrderCapitalAmount", "现场收款金额不允许空");
                        }

                        if (string.IsNullOrEmpty(Request.Form["PaymentTypeId"]))
                        {
                            AddFormError("PaymentTypeId", "支付方式不允许空");
                        }
                        long paymentTypeId;
                        if (!long.TryParse(Request.Form["PaymentTypeId"], out paymentTypeId))
                        {
                            AddFormError("PaymentTypeId", "支付方式不允许空");
                        }

                        if (!IsValid) return View(salesOrder);
                        #endregion

                        salesOrder.CreateTime = DateTime.Now;

                        #region 交货状态
                        if (salesOrder.DeliveryTypeId == DeliveryType.Delivery)
                        {
                            salesOrder.DeliveryStatusId = DeliveryStatus.NonDelivery;//交货状态
                        }
                        else {
                            salesOrder.DeliveryStatusId = DeliveryStatus.DeliveryComplete;//交货状态
                        }
                        #endregion

                        salesOrder.SettleedAmount = salesOrderCapitalAmount;//已结算金额
                        salesOrder.UnSettleedAmount = salesOrder.ActualAmount - salesOrder.SettleedAmount;//未结算金额
                        #region 结算状态
                        if (salesOrder.SettleedAmount <= 0) {
                            salesOrder.SettleStatusId = SettleStatus.UnSettleed;
                        }
                        if (salesOrder.SettleedAmount>0 && salesOrder.UnSettleedAmount > 0) {
                            salesOrder.SettleStatusId = SettleStatus.SettleedPart;
                        }
                        if (salesOrder.SettleedAmount > 0 && salesOrder.UnSettleedAmount <= 0 && salesOrder.SettleedAmount== salesOrder.ActualAmount)
                        {
                            salesOrder.SettleStatusId = SettleStatus.SettleedComplete;
                        }
                        #endregion

                        salesOrder.IsCompleted = false;
                        if (salesOrder.SettleStatusId == SettleStatus.SettleedComplete && salesOrder.DeliveryStatusId == DeliveryStatus.DeliveryComplete)
                        {
                            salesOrder.IsCompleted = true;
                        }

                        #region 修改客户表数据信息：应收款金额、未完成订单数量
                        MySqlCommand cmd = new MySqlCommand("update customer set ReceivableCapital=ReceivableCapital+@ReceivableCapital,NotCompletedOrderCount=NotCompletedOrderCount+@NotCompletedOrderCount,LatestOrderTime=@LatestOrderTime where CustomerId=@CustomerId");
                        cmd.Parameters.AddWithValue("@ReceivableCapital", salesOrder.UnSettleedAmount);
                        cmd.Parameters.AddWithValue("@NotCompletedOrderCount", salesOrder.IsCompleted?0:1);//未完成订单数量
                        cmd.Parameters.AddWithValue("@LatestOrderTime", salesOrder.CreateTime);//最近订货时间
                        cmd.Parameters.AddWithValue("@CustomerId", salesOrder.CustomerId);
                        cn.ExecuteNonQuery(cmd);
                        #endregion

                        cn.Insert(salesOrder);

                        #region 添加订单行
                        foreach (SalesOrderLine salesOrderLine in GetSalesOrderLines(salesOrder.SalesOrderId).Items) {
                            cn.Insert(salesOrderLine);

                            #region 修改库存表锁定数量，库存数量
                            UpdateStoreProduct(cn, salesOrderLine.Quantity, salesOrderLine.ProductId, salesOrderLine.LotNo, salesOrder.StoreId);
                            #endregion

                            #region 修改商品表锁定数量，可用数量，总数量
                            UpdateProduct(cn, salesOrderLine.Quantity, salesOrderLine.ProductId);
                            #endregion
                        }
                        #endregion

                        #region 添加资金流水
                        if (salesOrderCapitalAmount > 0)
                        {
                            SalesOrderCapital salesOrderCapital = new SalesOrderCapital();
                            salesOrderCapital.Amount = salesOrderCapitalAmount;
                            salesOrderCapital.CapitalTime = DateTime.Now;
                            salesOrderCapital.SalesOrderId = salesOrder.SalesOrderId;
                            salesOrderCapital.CapitalEmployeeId = CurrentEmployee.EmployeeId;
                            salesOrderCapital.PaymentTypeId = paymentTypeId;
                            cn.Insert(salesOrderCapital);
                        }
                        #endregion

                        #endregion
                    }
                    else
                    {
                        #region 修改
                        salesOrder.SalesOrderId = id.Value;
                        #region validate
                        ConditionExpressionCollection cs = new ConditionExpressionCollection();
                        cs.Add(SalesOrder_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                        cs.Add(SalesOrder_.SalesOrderNo.TEqual(salesOrder.SalesOrderNo));
                        cs.Add(SalesOrder_.SalesOrderId.TNotEqual(salesOrder.SalesOrderId));
                        if (cn.Exists<SalesOrder>(cs))
                        {
                            AddFormError(SalesOrder_.SalesOrderNo, "订单编号不允许重复");
                        }
                        if (!IsValid) return View(salesOrder);
                        #endregion

                        #region 查询老的订单信息
                        SalesOrder salesOrderFromDB = new SalesOrder { SalesOrderId = salesOrder.SalesOrderId };
                        cn.Select(salesOrderFromDB, SalesOrder_.StoreId);
                        #endregion

                        cn.Update(salesOrder, SalesOrder_.SalesOrderNo, SalesOrder_.SalesOrderTypeId, SalesOrder_.CustomerId, SalesOrder_.OrderEmployeeId,
                                           SalesOrder_.Address, SalesOrder_.ContactName, SalesOrder_.Phone, SalesOrder_.IsMapped,
                                           SalesOrder_.X, SalesOrder_.Y, SalesOrder_.Amount, SalesOrder_.ActualAmount, SalesOrder_.DeliveryRemark, SalesOrder_.DeliveryStatusId, SalesOrder_.DeliveryTime, SalesOrder_.DeliveryTypeId);
                        
                        #region 修改订单行
                        SalesOrderLines salesOrderLines1 = GetSalesOrderLines(salesOrder.SalesOrderId);
                        foreach (SalesOrderLine salesOrderLine in salesOrderLines1.Items) {
                            if (salesOrderLine.SalesOrderLineId > 0)
                            {
                                SalesOrderLine salesOrderLineFromDB = new SalesOrderLine { SalesOrderLineId = salesOrderLine.SalesOrderLineId };
                                cn.Select(salesOrderLineFromDB);
                                if (salesOrderLineFromDB.ProductId == salesOrderLine.ProductId)//如果还是同一个商品
                                {
                                    //如果还是同一批号的
                                    if (salesOrderLineFromDB.LotNo == salesOrderLine.LotNo)
                                    {
                                        #region 修改库存表锁定数量，库存数量(同批号的)
                                        UpdateStoreProduct(cn,
                                            salesOrderLine.Quantity - salesOrderLineFromDB.Quantity,
                                            salesOrderLine.ProductId,
                                            salesOrderLine.LotNo,
                                            salesOrder.StoreId);
                                        #endregion
                                    }
                                    else {
                                        #region 修改库存表锁定数量，库存数量(不同批号的)
                                        UpdateStoreProduct(cn,-salesOrderLineFromDB.Quantity,
                                            salesOrderLineFromDB.ProductId,
                                            salesOrderLineFromDB.LotNo, 
                                            salesOrder.StoreId);
                                        UpdateStoreProduct(cn,
                                            salesOrderLine.Quantity,
                                            salesOrderLine.ProductId,
                                            salesOrderLine.LotNo,
                                            salesOrder.StoreId);
                                        #endregion
                                    }

                                    #region 修改商品表锁定数量，可用数量，总数量
                                    UpdateProduct(cn, salesOrderLine.Quantity - salesOrderLineFromDB.Quantity, salesOrderLine.ProductId);
                                    #endregion
                                }
                                else {
                                    #region 修改为另一个商品了

                                    #region 修改库存表锁定数量，库存数量
                                    UpdateStoreProduct(cn, -salesOrderLineFromDB.Quantity, salesOrderLineFromDB.ProductId, salesOrderLineFromDB.LotNo, salesOrderFromDB.StoreId);
                                    UpdateStoreProduct(cn, salesOrderLine.Quantity, salesOrderLine.ProductId, salesOrderLine.LotNo, salesOrder.StoreId);
                                    #endregion

                                    #region 修改商品表锁定数量，可用数量，总数量
                                    UpdateProduct(cn, -salesOrderLineFromDB.Quantity, salesOrderLineFromDB.ProductId);
                                    UpdateProduct(cn, salesOrderLine.Quantity, salesOrderLine.ProductId);
                                    #endregion

                                    #endregion
                                }

                                cn.Update(salesOrderLine, SalesOrderLine_.ALL);
                            }
                            else {
                                cn.Insert(salesOrderLine);

                                #region 修改库存表锁定数量，库存数量
                                UpdateStoreProduct(cn, salesOrderLine.Quantity, salesOrderLine.ProductId, salesOrderLine.LotNo, salesOrder.StoreId);
                                #endregion

                                #region 修改商品表锁定数量，可用数量，总数量
                                UpdateProduct(cn, salesOrderLine.Quantity, salesOrderLine.ProductId);
                                #endregion
                            }
                        }

                        QueryExpression query = new QueryExpression();
                        query.EntityType = typeof(SalesOrderLine);
                        query.Selects.Add(SalesOrderLine_.SalesOrderLineId);
                        query.Selects.Add(SalesOrderLine_.Quantity);
                        query.Selects.Add(SalesOrderLine_.ProductId);
                        query.Selects.Add(SalesOrderLine_.LotNo);
                        query.Wheres.Add(SalesOrderLine_.SalesOrderId.TEqual(salesOrder.SalesOrderId));
                        SalesOrderLines salesOrderLines2 = new SalesOrderLines();
                        cn.SelectCollection(salesOrderLines2.Items, query);
                        foreach (SalesOrderLine salesOrderLine in salesOrderLines2.Items) {
                            if (salesOrderLines1.Items.Where(p => p.SalesOrderLineId == salesOrderLine.SalesOrderLineId).Count() <= 0) {
                                cn.Delete(salesOrderLine);
                                UpdateStoreProduct(cn, -salesOrderLine.Quantity, salesOrderLine.ProductId, salesOrderLine.LotNo, salesOrder.StoreId);
                                UpdateProduct(cn, -salesOrderLine.Quantity, salesOrderLine.ProductId);
                            }
                        }
                        #endregion

                        #endregion
                    }
                    cn.Commit();
                }
                catch(Exception ex)
                {
                    cn.Rollback();
                    throw new BusinessException(ex.Message);
                }
            }
            return new IframeResult(Url.Action("Edit"), Url.Action("Index"));
        }
       
        #endregion

        #region 订单详情
        public ActionResult Detail(long id)
        {
            SalesOrder salesOrder = new SalesOrder();
            if (id > 0)
            {
                ViewBag.Title = "销售订单详情-" + id;
                salesOrder.SalesOrderId = (long)id;
                using (IDbSession cn = OpenSession())
                {
                    cn.Select(salesOrder, SalesOrder_.ALL, SalesOrder_.OrderEmployee.EmployeeName, SalesOrder_.Customer.CustomerName, SalesOrder_.Store.StoreName);

                    #region 查询订单行
                    ViewData["salesOrderLines"] = GetSalesOrderLines(cn, salesOrder.SalesOrderId).Items;
                    #endregion
                }
            }
            return View(salesOrder);
        }
        #endregion

        #region 删除
        [HttpPost]
        public ActionResult Delete(long id)
        {
            SalesOrder salesOrder = new SalesOrder { SalesOrderId = id };
            using (IDbSession cn = OpenSession())
            {
                try
                {
                    cn.BeginTransaction();

                    cn.Select(salesOrder, SalesOrder_.DeliveryStatusId, SalesOrder_.SettleStatusId);
                    if (salesOrder.DeliveryStatusId > DeliveryStatus.NonDelivery) {
                        return LJson(false, "不能删除该订单，改订单已配送或者已配送完成");
                    }
                    if (salesOrder.SettleStatusId > SettleStatus.UnSettleed) {
                        return LJson(false, "不能删除该订单，该订单已结算过或者部分结算");
                    }

                    cn.Delete(salesOrder);

                    #region 修改客户表数据信息：应收款金额、未完成订单数量

                    #region 获取最后下单时间
                    QueryExpression query = new QueryExpression();
                    query.EntityType = typeof(SalesOrder);
                    query.Selects.Add(SalesOrder_.CreateTime);
                    query.OrderBys.Add(SalesOrder_.CreateTime.Desc);
                    query.PageSize = 1;
                    query.PageIndex = 1;
                    SalesOrders salesOrders1 = new SalesOrders();
                    cn.SelectCollection(salesOrders1.Items, query);
                    DateTime? latestOrderTime = null;
                    if (salesOrders1.Items.Count > 0) {
                        latestOrderTime = salesOrders1.Items[0].CreateTime;
                    }
                    #endregion
                    MySqlCommand cmd = new MySqlCommand("update customer set ReceivableCapital=ReceivableCapital+@ReceivableCapital,NotCompletedOrderCount=NotCompletedOrderCount+@NotCompletedOrderCount,LatestOrderTime=@LatestOrderTime where CustomerId=@CustomerId");
                    cmd.Parameters.AddWithValue("@ReceivableCapital", -salesOrder.UnSettleedAmount);
                    cmd.Parameters.AddWithValue("@NotCompletedOrderCount", -1);//未完成订单数量
                    cmd.Parameters.AddWithValue("@LatestOrderTime",latestOrderTime);//最近订货时间
                    cmd.Parameters.AddWithValue("@CustomerId", salesOrder.CustomerId);
                    cn.ExecuteNonQuery(cmd);
                    #endregion

                    #region 删除订单行
                    foreach (SalesOrderLine salesOrderLine in GetSalesOrderLines(cn, salesOrder.SalesOrderId).Items)
                    {
                        cn.Delete(salesOrderLine);
                        UpdateProduct(cn, -salesOrderLine.Quantity,salesOrderLine.ProductId);
                        UpdateStoreProduct(cn, -salesOrderLine.Quantity, salesOrderLine.ProductId, salesOrderLine.LotNo, salesOrder.StoreId);
                    }
                    #endregion
                    cn.Commit();
                }
                catch (Exception ex)
                {
                    cn.Rollback();
                    return LJson(false, "删除失败：" + ex.Message);
                }
            }
            return LJson(true,"删除成功");
        }

        #endregion

        #region 销售出库
        public ActionResult SellingOut(int? p)
        {
            int pageIndex = p == null ? 1 : (int)p;
            ViewBag.PageIndex = pageIndex;

            using (IDbSession cn = OpenSession())
            {
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(SalesOrder);
                q.Selects.Add(SalesOrder_.SalesOrderId);
                q.Selects.Add(SalesOrder_.SalesOrderNo);//销售单号
                q.Selects.Add(SalesOrder_.CustomerId);//客户
                q.Selects.Add(SalesOrder_.Customer.CustomerName);//客户
                q.Selects.Add(SalesOrder_.Address);//收货人
                q.Selects.Add(SalesOrder_.ContactName);//收货人
                q.Selects.Add(SalesOrder_.OrderEmployeeId);//业务员ID
                q.Selects.Add(SalesOrder_.OrderEmployee.EmployeeName);//业务员ID
                q.Selects.Add(SalesOrder_.Phone);//联系电话
                q.Selects.Add(SalesOrder_.IsCompleted);//是否结束
                q.Selects.Add(SalesOrder_.DeliveryStatusId);//交货状态
                q.Selects.Add(SalesOrder_.SettleStatusId);//结款状态
                q.Wheres.Add(SalesOrder_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                q.Wheres.Add(SalesOrder_.DeliveryTypeId.TEqual(DeliveryType.Delivery));//交货类型是我方配送
                q.Wheres.Add(SalesOrder_.DeliveryStatusId.TEqual(DeliveryStatus.NonDelivery));//交货状态是：未发货
                q.OrderBy(SalesOrder_.CreateTime.Asc);
                q.ReturnMatchedCount = true;
                q.PageIndex = pageIndex;
                q.PageSize = 8;
                SalesOrders SalesOrders = new SalesOrders();
                SalesOrders.TotalCount = cn.SelectCollection(SalesOrders.Items, q);
                return View(SalesOrders);
            }
        }

        [HttpPost]
        public ActionResult SalesOrderLine(long salesOrderId)
        {
            using (IDbSession cn = OpenSession())
            {
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(SalesOrderLine);
                q.Selects.Add(SalesOrderLine_.SalesOrderId);
                q.Selects.Add(SalesOrderLine_.ProductId);
                q.Selects.Add(SalesOrderLine_.ProductName);
                q.Selects.Add(SalesOrderLine_.ProductNo);
                q.Selects.Add(SalesOrderLine_.Spec);
                q.Selects.Add(SalesOrderLine_.LotNo);
                q.Selects.Add(SalesOrderLine_.Quantity);
                q.Selects.Add(SalesOrderLine_.Price);
                q.Selects.Add(SalesOrderLine_.Amount);
                q.Selects.Add(SalesOrderLine_.Remark);
                q.Wheres.Add(SalesOrderLine_.SalesOrderId.TEqual(salesOrderId));
                SalesOrderLines salesOrderLines = new SalesOrderLines();
                cn.SelectCollection(salesOrderLines.Items, q);
                return Json(salesOrderLines);
            }
        }

        /// <summary>
        /// 出库
        /// </summary>
        /// <param name="salesOrderId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SellingOut(long salesOrderId)
        {
            using (IDbSession cn = OpenSession())
            {
                try {
                    cn.BeginTransaction();

                    #region 查询订单数据 和 订单行数据
                    SalesOrder salesOrder = new SalesOrder { SalesOrderId = salesOrderId };
                    cn.Select(salesOrder, SalesOrder_.StoreId);

                    QueryExpression query = new QueryExpression();
                    query.EntityType = typeof(SalesOrderLine);
                    query.Selects.Add(SalesOrderLine_.Quantity);
                    query.Selects.Add(SalesOrderLine_.LotNo);
                    query.Selects.Add(SalesOrderLine_.ProductId);
                    query.Wheres.Add(SalesOrderLine_.SalesOrderId.TEqual(salesOrderId));
                    SalesOrderLines salesOrderLines = new SalesOrderLines();
                    cn.SelectCollection(salesOrderLines.Items, query);
                    #endregion

                    foreach (SalesOrderLine salesOrderLine in salesOrderLines.Items)
                    {
                        #region 商品库存表
                        MySqlCommand cmdStoreProduct = new MySqlCommand("update StoreProduct set UseableQuantity=UseableQuantity+@UseableQuantity,LockQuantity=LockQuantity+@LockQuantity,Quantity=Quantity+@Quantity where ProductId=@ProductId and LotNo=@LotNo and StoreId=@StoreId");
                        cmdStoreProduct.Parameters.AddWithValue("@UseableQuantity",0);
                        cmdStoreProduct.Parameters.AddWithValue("@LockQuantity", -salesOrderLine.Quantity);
                        cmdStoreProduct.Parameters.AddWithValue("@Quantity", -salesOrderLine.Quantity);
                        cmdStoreProduct.Parameters.AddWithValue("@ProductId", salesOrderLine.ProductId);
                        cmdStoreProduct.Parameters.AddWithValue("@LotNo", salesOrderLine.LotNo);
                        cmdStoreProduct.Parameters.AddWithValue("@StoreId",salesOrder.StoreId);
                        cn.ExecuteNonQuery(cmdStoreProduct);
                        #endregion

                        #region 商品表
                        MySqlCommand cmdProduct = new MySqlCommand("update Product set LockCount=LockCount+@LockCount,UseableCount=UseableCount+@UseableCount,StoreCount=StoreCount+@StoreCount where ProductId=@ProductId");
                        cmdProduct.Parameters.AddWithValue("@LockCount", -salesOrderLine.Quantity);
                        cmdProduct.Parameters.AddWithValue("@StoreCount",-salesOrderLine.Quantity);
                        cmdProduct.Parameters.AddWithValue("@UseableCount",0);
                        cmdProduct.Parameters.AddWithValue("@ProductId", salesOrderLine.ProductId);
                        cn.ExecuteNonQuery(cmdProduct);
                        #endregion
                    }

                    #region 修改交货状态
                    salesOrder.DeliveryStatusId = DeliveryStatus.Delivery;
                    cn.Update(salesOrder, SalesOrder_.DeliveryStatusId);
                    #endregion

                    cn.Commit();
                    return LJson(true,"出库成功");
                }
                catch {
                    cn.Rollback();
                    return LJson(false,"出库失败");
                }
            }
        }
        #endregion
    }
}
